﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using CreditAgricole.Framework;
using CreditAgricole.Application;
using System.Data;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using System.Net;
using System.Xml;
using System.Xml.Linq;
using Microsoft.SharePoint;

namespace CreditAgricole.PageCodeBehind
{
    public class DetailedGridView : GridView
    {
        private List<VOBase> allObjs;

        public List<VOBase> BaseObjs
        {
            get { return allObjs; }
            set { allObjs = value; }
        }
        private int mepCounter;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            mepCounter = 0;
            BindToGridView();
        }

        #region Tool Methods

        private void InsertDataInTable(List<VOBase> selectedItems, DataTable table)
        {
            foreach (VOBase result in selectedItems)
            {
                DataRow row = table.Rows.Add();
                Dictionary<string, string> properties = result.PropertiesToDisplay;
                foreach (KeyValuePair<string, string> pair in properties)
                {
                    row[pair.Key] = pair.Value;
                }
            }
        }

        private void CreateColumns(DataTable table, List<string> objProperties)
        {
            foreach (string propertyValue in objProperties)
            {
                table.Columns.Add(propertyValue);
            }
        }

        private SPBoundField CreateBoundField(string fieldName)
        {
            SPBoundField boundField = new SPBoundField();
            boundField.HeaderText = fieldName;
            boundField.DataField = fieldName;
            boundField.ItemStyle.Wrap = true;
            return boundField;
        }

        #endregion

        /// <summary>
        /// Create a this, bind all data and disply it
        /// </summary>
        /// <param name="selectedItems">Data to bind in this</param>
        private void BindToGridView()
        {
            this.CssClass = "mGrid";
            this.AllowPaging = true;
            this.PageSize = 30;
            this.PagerStyle.CssClass = "pagerclass";
            DataTable table = new DataTable();
            List<string> propertiesToDisplay = BaseObjs.First().PropertiesToDisplay.Keys.ToList();
            CreateColumns(table, propertiesToDisplay);
            InsertDataInTable(BaseObjs, table);
            foreach (string propertyValue in propertiesToDisplay)
            {
                this.Columns.Add(CreateBoundField(propertyValue));
            }
            this.AutoGenerateColumns = false;

            this.RowDataBound += new GridViewRowEventHandler(gview_OnInsertRow);
            this.PageIndexChanging += new GridViewPageEventHandler(gview_OnPageIndexChanging);
            this.DataSource = table.DefaultView;
            this.DataBind();
        }

        #region Events

        /// <summary>
        /// Event to call when a datarow is created. It adds a hidden row where further details are stored
        /// </summary>
        /// <param name="sender">this where data is inserted</param>
        /// <param name="e">Event Handler</param>
        protected void gview_OnInsertRow(object sender, GridViewRowEventArgs e)
        {
            switch (e.Row.RowType)
            {
                case DataControlRowType.DataRow:
                    {
                        int colSpan = this.Columns.Count;
                        TableCell tCell = new TableCell();
                        tCell.Attributes["ColSpan"] = MappingTool.CatchNull(colSpan);

                        Panel pnlDetail = new Panel();
                        pnlDetail.CssClass = "detailedPanel";
                        tCell.Controls.Add(pnlDetail);
                        VOBase currentObj = allObjs[mepCounter];
                        if (currentObj.NeedsApproval == true)
                        {
                            #region Ajout des boutons pour approbation
                            Panel pnlApproveBlock = new Panel();
                            pnlApproveBlock.CssClass = "approveBlock";
                            Panel pnlHeaderApproveBlock = new Panel();
                            pnlHeaderApproveBlock.CssClass = "headerApproveBlock";
                            Label lblApproveBlock = new Label();
                            lblApproveBlock.Text = "Approuver/Rejeter le document";
                            Image imgArrow = new Image()
                            {
                                ImageUrl = "/_layouts/1033/images/ewr074.gif"
                            };
                            pnlHeaderApproveBlock.Controls.Add(lblApproveBlock);
                            pnlHeaderApproveBlock.Controls.Add(imgArrow);
                            pnlApproveBlock.Controls.Add(pnlHeaderApproveBlock);

                            Panel pnlApprovalButtons = new Panel();
                            pnlApprovalButtons.CssClass = "buttonsApproveBlock";
                            Button rejectWFButton = new Button();
                            rejectWFButton.Text = "Rejeter le document";
                            rejectWFButton.OnClientClick = string.Format("RejectWorkflow('{0}','{1}'); return false;", currentObj.DocUrl, currentObj.WebUrl);
                            Button approveWFButton = new Button();
                            approveWFButton.Text = "Approuver le document";
                            approveWFButton.OnClientClick = string.Format("ApproveWorkflow('{0}','{1}'); return false;", currentObj.DocUrl, currentObj.WebUrl);
                            TextBox txtComment = new TextBox()
                            {
                                TextMode = TextBoxMode.MultiLine,
                                Rows = 5,
                                Columns = 70,
                            };
                            Image imgLoading = new Image()
                            {
                                ImageUrl = "/_layouts/images/gears_anv4.gif"
                            };
                            pnlApprovalButtons.Controls.Add(imgLoading);
                            pnlApprovalButtons.Controls.Add(txtComment);
                            pnlApprovalButtons.Controls.Add(new LiteralControl("<br />"));
                            pnlApprovalButtons.Controls.Add(approveWFButton);
                            pnlApprovalButtons.Controls.Add(rejectWFButton);
                            pnlApproveBlock.Controls.Add(pnlApprovalButtons);
                            pnlDetail.Controls.Add(pnlApproveBlock);
                            #endregion
                        }
                        Dictionary<string, object> details = currentObj.DetailsToDisplay;

                        #region Ajout des elements details

                        foreach (KeyValuePair<string,object> pair in details)
                        {
                            Panel pnlDetailedInfo = new Panel();
                            Label lblKey = new Label();
                            lblKey.Text = pair.Key;
                            pnlDetailedInfo.Controls.Add(lblKey);
                            pnlDetailedInfo.Controls.Add(new LiteralControl("<br />"));
                            if (pair.Value.GetType() == typeof(string))
                            {
                                Label lblValue = new Label();
                                lblValue.Text = MappingTool.CatchNull(pair.Value);
                                pnlDetailedInfo.Controls.Add(lblValue);
                            }
                            else
                            {
                                List<string> values = pair.Value as List<string>;
                                HtmlGenericControl listValues = new HtmlGenericControl("UL");
                                foreach (string val in values)
                                {
                                    HtmlGenericControl itemValue = new HtmlGenericControl("li");
                                    Label lblValue = new Label();
                                    lblValue.Text = val;
                                    itemValue.Controls.Add(lblValue);
                                    listValues.Controls.Add(itemValue);
                                }
                                pnlDetailedInfo.Controls.Add(listValues);
                            }
                            pnlDetail.Controls.Add(pnlDetailedInfo);
                        }
                        #endregion

                        #region Ajout du bouton visualisation du document
                        Panel pnlPreviewDoc = new Panel();
                        pnlPreviewDoc.Width = 30;
                        pnlPreviewDoc.Height = 15;
                        pnlPreviewDoc.CssClass = "just_to_push";
                        UpdateListItem popupToUpdate = this.Page.LoadControl("~/_controltemplates/CreditAgricole.CustomControl/UpdateListItem.ascx") as UpdateListItem;
                        popupToUpdate.mepToUpdate = currentObj as VOMep;
                        this.Page.Form.Controls.Add(popupToUpdate);
                        pnlDetail.Controls.Add(pnlPreviewDoc);
                        #endregion
                        GridViewRow gRow = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
                        gRow.CssClass = "hiddenRow";
                        gRow.Cells.Add(tCell);

                        Table tbl = (Table)e.Row.Parent;
                        tbl.Controls.AddAt(this.Controls[0].Controls.Count, gRow);
                        mepCounter++;
                        break;
                    }
                case DataControlRowType.Pager:
                    {
                        TableCell cell = e.Row.Cells[0];
                        if (cell.Controls[0] != null)
                        {
                            TableRow row = cell.Controls[0].Controls[0] as TableRow;
                            row.CssClass = "pagerclass";
                        }
                        break;
                    }
            }
        }

        protected void gview_OnPageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView gView = (GridView)sender;
            gView.PageIndex = e.NewPageIndex;
            gView.DataBind();
        }

        #endregion
    }
}
